const MenuButton = wx.getMenuButtonBoundingClientRect();
import request from "../../utils/request"
Page({
  data: {
    mHeight: MenuButton.height,
    type: [],
    list: [],
    total: 0,
    page: 1,
    currentId: 1
  },
  tabChange(e) {
    const id = e.detail.name; // 获取当前选中的分类id
    this.setData({
      currentId: id,
      page: 1,
      list: []
    })
    this.getList(id);
  },
  async getList(id) { // 加载商品列表
    wx.showLoading({
      title: '',
      mask: true
    })
    const res = await request.get(`/product/page?categoryId=${id}&pageNum=${this.data.page}`);
    const list = [];
    res.data.data.forEach((item, index) => {
      const col = index % 2
      if (!list[col]) {
        list[col] = []
      }
      list[col].push(item)
    })
    if (list[0] && this.data.list[0]) {
      list[0] = [...this.data.list[0], ...list[0]];
    }
    if (list[1] && this.data.list[1]) {
      list[1] = [...this.data.list[1], ...list[1]];
    }
    this.setData({
      list,
      total: res.data.total
    })
    console.log(res.data);
    wx.hideLoading();
  },
  async getType() { // 加载商品分类
    wx.showLoading({
      mask: true
    })
    const res = await request.get(`/category/list`);
    console.log(res.data.data);
    this.setData({
      type: res.data.data
    })
    wx.hideLoading();
  },
  onLoad() {
    this.getType();
    this.getList(1);
  },
  onReachBottom() {
    if (this.data.list[0].length + this.data.list[1].length < this.data.total) {
      this.data.page++;
      this.getList(this.data.currentId);
    } else {
      wx.showToast({
        title: '到底了～',
        icon: "none"
      })
    }
  }
})